<template>
  <div class="pages">
    <div class="pageLevel">
      <el-button v-if="!canSave" type="primary" class="go-back" @click="goBack()" size="small " style="margin-top:25px;margin-left:50px;">返回</el-button>
      <el-form :model="formData" :rules="rules" ref="formData" :disabled="!canSave" label-width="120px" size="small" style="margin-top:25px;">
        <el-form-item label="券批次名称" prop="activityName">
          <el-input style="width:250px;" v-model="formData.activityName" maxlength="30"></el-input>
        </el-form-item>
        <el-form-item label="优惠券" prop="ticketList">
          <el-button type="primary" @click="clickSelectTickets()" v-if='canSave'>选择优惠券</el-button>
        </el-form-item>
        <el-form-item>
          <el-table max-height="250" :data="formData.ticketList" style="width: 80%">
            <el-table-column prop="ticketName" align="center" label="优惠券标题" width="100"></el-table-column>
            <el-table-column prop="ticketSubName" align="center" label="优惠券副标题" width="120"></el-table-column>
            <el-table-column prop="ticketType" :formatter="ticketType" align="center" width="100" label="优惠券类型"> </el-table-column>
            <el-table-column prop="validDay" align="center" label="有效期"></el-table-column>
            <el-table-column prop="createTime" align="center" label="创建时间" width="160"></el-table-column>
            <el-table-column prop="sendCount" align="center" label="发放数量">
              <template slot-scope="scope">
                <el-input v-show="canSave" v-model="scope.row.sendCount" maxlength='1' onafterpaste="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}" oninput="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}"></el-input>
                <span v-show="!canSave">{{scope.row.sendCount}}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="操作">
              <template slot-scope="scope">
                <el-button type="text" @click="deleteTicket(scope.$index, formData.ticketList)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>

        <el-form-item label="发放范围" prop="activityCrowd" class="activityPeople">
          <el-radio-group @change="changePeopleRange" v-model="formData.activityCrowd">
            <el-radio label="2">按会员等级发放</el-radio>
            <el-radio label="3">自定义会员范围</el-radio>
            <el-radio label="4">指定会员发放</el-radio>
            <!-- 选择自定义会员 -->
            <div v-show="Grade" class="memLevelContent">
              <el-button type="primary" @click="clickSelectStores()">添加会员等级</el-button>
              <el-table max-height="250" :data="formData.gradeList" style="width: 100%">
                <el-table-column prop="levelName" label="等级名称" align="center"></el-table-column>
                <el-table-column prop="shopName" align="center" label="会员等级所属"></el-table-column>
                <el-table-column align="center" label="操作">
                  <template slot-scope="scope">
                    <el-button type="text" @click="deleteTicket(scope.$index, formData.gradeList)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div v-show="diymem" class="memLevelContent">
              <el-form inline size="mini" :model="formData" label-width="100px">
                <el-row>
                  <el-form-item label="订单类型" prop="orderType">
                    <el-select size="mini" v-model="formData.orderType" placeholder="全部" :disabled="!canSave" @change="empty">
                      <el-option label="商品订单" value="0"></el-option>
                      <el-option label="次卡订单" value="1"></el-option>
                      <el-option label="服务订单" value="2"></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="订单时间" prop="orderDate">
                    <el-date-picker v-model="formData.orderDate" value-format="yyyy-MM-dd" format="yyyy-MM-dd" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" :disabled="!canSave"></el-date-picker>
                  </el-form-item>
                </el-row>
                <el-row>
                  <el-form-item label="消费次数" prop="payNum">
                    <el-input :disabled="!canSave" v-model="formData.payNum" maxlength='8' onafterpaste="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}" oninput="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}"></el-input>
                  </el-form-item>
                  <el-form-item label="订单金额" prop="moneyMin">
                    <sd-input :val.sync='formData.moneyMin' :disableds="!canSave"></sd-input>
                  </el-form-item>
                  <el-form-item label="" label-width="0">
                    <span>----</span>
                  </el-form-item>
                  <el-form-item label-width="0" prop="moneyMax">
                    <sd-input :val.sync='formData.moneyMax' :disableds="!canSave"></sd-input>

                  </el-form-item>
                </el-row>
                <el-row v-show="formData.orderType=='0'">
                  <el-form-item label="购买品类">
                    <el-select v-model="formData.typeId" placeholder="请选择" :disabled="!canSave" clearable>
                      <el-option v-for="item in commodityCategoryfunList" :key="item.id" :label="item.label" :value="item.id"></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="购买品牌">
                    <el-select v-model="formData.brandId" placeholder="请选择" :disabled="!canSave" clearable>
                      <el-option v-for="item in commodityBrandList" :key="item.brandId" :label="item.brandName" :value="item.brandId"></el-option>
                    </el-select>
                  </el-form-item>
                </el-row>
                <el-form-item label="">
                  <el-button type="primary" @click="getMemNum" :disabled="!canSave">筛选</el-button>
                </el-form-item>
                <el-form-item label="">
                  <el-button @click="resetman" :disabled="!canSave">重置</el-button>
                </el-form-item>
                <el-form-item label="统计" label-width="50px">
                  <el-input disabled v-model="statisticsNum"></el-input>
                </el-form-item>
              </el-form>
            </div>
            <div v-show="memLevel" class="memLevelContent-list">
              <el-button v-if='canSave' type="primary" @click="clickSelectH5Page()">添加会员</el-button>
              <el-button v-if='canSave' type="danger" style="margin-left:15px;" size='small' @click='deleted()'>批量删除</el-button>
              <el-button v-if='canSave' type="primary" style="margin-left:200px;" @click="donwloadMb()">下载模板</el-button>
              <div style="float: right;margin-top:-10px;" v-if='canSave'>
                <a href="javascript:;" class="file">
                  批量导入
                  <input ref="uploading" @change="uploading($event)" type="file">
                </a>
              </div>
              <el-table max-height="250" :data="formData.shopList" style="width: 100%" @selection-change="changeFunDelete_good">
                <el-table-column type="selection" width="55" align="center" v-if='canSave'></el-table-column>

                <el-table-column prop="memberCode" label="会员编码" align="center" width="145"></el-table-column>
                <el-table-column prop="memberName" align="center" label="姓名"></el-table-column>
                <el-table-column prop="phone" align="center" label="手机号"></el-table-column>

                <el-table-column align="center" label="操作">
                  <template slot-scope="scope">
                    <el-button type="text" @click="deleteTicket(scope.$index, formData.shopList)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="发放时间" prop="paymentTime" class="activityPeople">
          <el-radio-group @change="changeRange" v-model="paymentTime">
            <el-radio :label="0">即时发放</el-radio>
            <el-radio :label="1">定时发放</el-radio>
            <div v-show="paymentTime==1" class="memLevelContent">
              <el-date-picker v-model="formData.fixedTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期时间">
              </el-date-picker>
            </div>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="创建人：">
          <el-input style="width:250px;" v-model="formData.creator" disabled></el-input>
        </el-form-item>
      </el-form>
      <div class="conserve">
        <div class="conserve-box">
          <el-button v-if="canSave" type="primary" @click="saveAct('formData')" size="medium ">保存</el-button>
          <el-button v-if="canSave" type="primary" class="go-back" @click="goBack()" size="medium " style="margin-left:25px;">返回</el-button>
        </div>
      </div>
      <!-- 会员等级弹窗 -->
      <el-dialog title="选择会员等级" :visible.sync="dialogStore" :closeOnClickModal='false' :closeOnPressEscape='false'>
        <div class="tableSearch">
          <el-form size="mini">
            <el-row>
              <el-form-item label="等级名称" label-width="90px">
                <el-input v-model="selectData.storeName" placeholder="请输入等级名称"></el-input>
              </el-form-item>
              <el-form-item label="会员等级所属" label-width="160px">
                <el-select v-model="selectData.storeType" placeholder="请选择" style="width:180px;">
                  <el-option v-for="item in storeArr" :key="item.id" :label="item.name" :value="item.id"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="" label-width="10px">
                <el-button type="primary" @click="searchStore()">查询</el-button>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="" label-width="10px">
                <el-button type="primary" @click="confirmSelectStore()">选择</el-button>
              </el-form-item>
              <el-form-item label="" label-width="10px">
                <el-button @click="dialogStore=false">取消</el-button>
              </el-form-item>
            </el-row>
          </el-form>
        </div>
        <el-table :data="tableDataDialogStore" max-height="300" ref="multipleTableStore" @selection-change="selectStore">
          <el-table-column type="selection" width="50"></el-table-column>
          <el-table-column prop="levelName" label="等级名称" align="center"></el-table-column>
          <el-table-column prop="shopName" align="center" label="会员等级所属"></el-table-column>
        </el-table>
        <page-unit :pageData="pageDataStore" :func="getStore"></page-unit>
      </el-dialog>

      <!-- 选择会员弹窗 -->
      <el-dialog title="选择会员" :visible.sync="dialogH5Page" :closeOnClickModal='false' :closeOnPressEscape='false' width="50%">
        <div class="tableSearch">
          <el-form size="mini">
            <el-row>
              <el-form-item label="">
                <el-input v-model="selectData.phone" size="mini" placeholder="请输入会员手机号"></el-input>
              </el-form-item>
              <el-form-item label="" label-width="15px">
                <el-button type="primary" size="mini" @click="searchSelect" class="Button">查询</el-button>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="" label-width="10px">
                <el-button type="primary" @click=" confirmSelectMember()">选择</el-button>
              </el-form-item>
              <el-form-item label="" label-width="10px">
                <el-button @click="dialogH5Page=false">取消</el-button>
              </el-form-item>
            </el-row>
          </el-form>
        </div>
        <el-table :data="tableDataDialogH5Page" max-height="300" ref="multipleTableH5Page" @selection-change="selectH5Page">
          <el-table-column type="selection" width="50"></el-table-column>
          <el-table-column type="index" label="序号" align="center"></el-table-column>
          <el-table-column prop="memberCode" label="会员编码" align="center"></el-table-column>
          <el-table-column prop="name" label="姓名" align="center"></el-table-column>
          <el-table-column prop="phone" label="手机号" align="center"></el-table-column>
        </el-table>
        <page-unit :pageData="pageDataH5Page" :func="h5ConfigList"></page-unit>
      </el-dialog>
      <!-- 优惠券弹窗 -->
      <el-dialog title="选择优惠券" :visible.sync="dialogTicket" :closeOnClickModal='false' :closeOnPressEscape='false'>
        <div class="tableSearch">
          <el-form size="mini">
            <el-row>
              <el-form-item label="优惠券名称" label-width="100px">
                <el-input v-model="selectData.ticketName" placeholder="请输入优惠券名称"></el-input>
              </el-form-item>
              <el-form-item label="" label-width="10px">
                <el-button type="primary" @click="searchTicket()">查询</el-button>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="" label-width="10px">
                <el-button type="primary" @click="confirmSelectTicket()">选择</el-button>
              </el-form-item>
              <el-form-item label="" label-width="10px">
                <el-button @click="dialogTicket=false">取消</el-button>
              </el-form-item>
            </el-row>
          </el-form>
        </div>
        <el-table :data="tableDataDialogTicket" max-height="300" ref="multipleTableTicket" @selection-change="selectTicket">
          <el-table-column type="selection" width="50"></el-table-column>
          <el-table-column prop="ticketName" label="优惠券标题" align="center"></el-table-column>
          <el-table-column prop="ticketSubName" label="优惠券副标题" align="center"></el-table-column>
          <el-table-column prop="ticketType" :formatter="ticketType" align="center" label="优惠券类型"></el-table-column>
          <el-table-column prop="validDay" label="有效期时间" align="center"></el-table-column>
          <el-table-column prop="ticketState" :formatter="cardStutas" label="状态" align="center"></el-table-column>
          <el-table-column prop="createTime" label="创建时间" align="center" width="160"></el-table-column>
        </el-table>
        <page-unit :pageData="pageDataTicket" :func="getCard"></page-unit>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { mapState } from "vuex";
import pageUnit from "@/components/Page";
import util from "@/util";
import state from "@/util/state";
import sdInput from "@/components/SdInput";
import {
  saveOrUpdateActivity,
  saveOrUpdateTicketSend,
  listMemberLevel,
  ticketSendCountMember,
  memberListPage,
  findMarketTicketListPage,
  selectTicketSendDetail,
  listMemberLevelOfTicket,
  brandDetail,
  getTreeList,
  leadPhone,
  selectBaseShopPageList
} from "@/api";
export default {
  components: { pageUnit, sdInput },
  computed: mapState([
    "pageLevel",
    "merchantId",
    "companyName",
    "sub",
    "userInfo",
    "linkName",
    "isShop",
    "mobile"
  ]),
  data() {
    return {
      shopType: state.shopType,
      ticketType: state.ticketType,
      cardStutas: state.cardStutas,
      countList: [],
      sourceType: "",
      canSave: false, // 是否显示保存按钮
      levelL: [], // 选择的会员等级
      showTips: false, // 是否显示优惠券提示
      commodityBrandList: [], // 自定义会员购买品牌数组
      commodityCategoryfunList: [], // 自定义会员购买品类数组
      tableDataDialogTicket: [], // 弹窗优惠券数组
      tableDataDialogStore: [], // 弹窗会员等级数组
      tableDataDialogMsg: [], // 弹窗短信数组
      tableDataDialogH5Page: [], // 弹窗会员数组
      dialogTicket: false, // 优惠券弹窗
      dialogStore: false, // 会员等级弹窗
      dialogH5Page: false, // h5配置弹窗
      mutableStore: [], // 多选选择门店存入的数组
      mutableTicket: [], // 多选选择优惠券存入的数组
      singleMsg: "", // 单选短信数组
      singleH5Page: [], // 单选H5页面数组
      memLevel: false, // 是否显示会员等级
      Grade: false,
      diymem: false, // 是否显示自定义会员表单
      memberList: [], // 会员等级数组
      statisticsNum: 0,
      paymentTime: 0,
      formData: {
        orderType: "0",
        paymentTime: 0, //发放时间
        fixedTime: "", //定时发放时间
        creator: "", // 操作人
        orgId: "", //组织结构id
        activityName: "", //券批次名称
        activityCrowd: "2", //活动人群  -会员等级，3-自定义会员,4-指定会员
        activityCrowdRue: [], //自定义会员
        timeEnd: "", //优惠券结束时间
        payNum: "", //消费次数
        moneyMin: "", //客单价（最小值）
        moneyMax: "", //客单价（this.最大值）
        typeId: "", //品类id
        brandId: "", //品牌id
        peopleNum: 0, // 自定义统计会员
        urlId: "", //h5链接地址
        msgTemplateName: "", //短信模板内容
        gradeList: [],
        shopList: [],
        ticketList: [],
        deleteList: [],
        orderDate: []
      },
      rules: {
        activityName: [
          { required: true, message: "请输入券批次名称", trigger: "blur" },
          { min: 1, max: 30, message: "长度在 1 到 30 个字符", trigger: "blur" }
        ],
        ticketList: [
          { required: true, message: "请选择优惠券", trigger: "blur" }
        ],
        activityCrowd: [
          {
            required: true,
            message: "请至少选择一类活动人群",
            trigger: "change"
          }
        ],
        payNum: [{ validator: util.validateParkingLot, trigger: "blur" }],
        moneyMin: [{ validator: util.validatenum1, trigger: "blur" }],
        moneyMax: [{ validator: util.validateParkingLot, trigger: "blur" }]
      },
      storeArr: [], // 门店列表

      pageDataTicket: {
        pageSize: 5,
        currentPage: 1,
        totalItems: 0,
        pageSizeArr: [5, 10, 20]
      },
      pageDataStore: {
        pageSize: 5,
        currentPage: 1,
        totalItems: 0,
        pageSizeArr: [5, 10, 20]
      },
      pageDataMsg: {
        pageSize: 5,
        currentPage: 1,
        totalItems: 0,
        pageSizeArr: [5, 10, 20]
      },
      pageDataH5Page: {
        pageSize: 5,
        currentPage: 1,
        totalItems: 0,
        pageSizeArr: [5, 10, 20]
      },
      selectData: {
        storeName: "", // 门店名称
        storeType: "", // 门店类型
        phone: "", //会员手机号
        ticketName: "", // 优惠券关键字

        msgCode: "" // 短信code
      }
    };
  },
  watch: {
    statisticsNum(value) {
      this.formData.peopleNum = value;
    }
  },
  mounted() {
    let id = util.getQuery().id;
    var types = util.getQuery().type;

    if (types == "add") {
      // 新增
      this.canSave = true;
    } else {
      if (types == "lock") {
        // 查看
        this.canSave = false;
        this.details();
      } else if (types == "see") {
        // 编辑
        this.canSave = true;
        this.details();
      }
    }
    this.init();
    this.getMemberLevel();
    this.commodityCategoryfun();
    this.commodityBrand();
    this.changePeopleRange();
  },
  methods: {
    // 获取门店
    _selectBaseShopPageList() {
      selectBaseShopPageList({
        businessId: this.merchantId,
        type: 3
      }).then(res => {
        let isStore = {
          id: this.merchantId,
          name: this.companyName
        };
        let whole = {
          id: "",
          name: "全部"
        };
        this.storeArr = res.data.list;
        if (this.isShop != "0") {
          this.storeArr.unshift(isStore);
        }
        this.storeArr.unshift(whole);
      });
    },
    changeRange(val) {
      // console.log(val);
    },
    uniqueMemberId(arr) {
      const res = new Map();
      return arr.filter(
        arr => !res.has(arr.memberCompanyId) && res.set(arr.memberCompanyId, 1)
      );
    },
    uniqueId(arr) {
      const res = new Map();
      return arr.filter(arr => !res.has(arr.id) && res.set(arr.id, 1));
    },
    // 上传文件
    uploading(event) {
      this.file = event.target.files[0]; //获取文件
      var windowURL = window.URL || window.webkitURL;
      //创建图片文件的url
      this.src = windowURL.createObjectURL(event.target.files[0]);
      //取消默认行为
      let formdata = new FormData();
      formdata.append("file", this.file);
      formdata.append("orgId", this.merchantId);
      this.loading = true;
      leadPhone(formdata)
        .then(res => {
          if (res.code == "200") {
            let arrs = this.formData.shopList.concat(res.data);
            this.formData.shopList = this.uniqueMemberId(arrs);
            // console.log(this.formData.shopList);
            this.$refs.uploading.value = null;
            this.loading = false;
            this.$message({
              showClose: true,
              message: res.msg,
              type: "success"
            });
          }
        })
        .catch(error => {})
        .finally((this.$refs.uploading.value = null));
    },
    donwloadMb() {
      let url = "";
      window.open(
        (url =
          "https://article.mumzone.cn/%E4%BC%98%E6%83%A0%E5%8A%B5%E7%9B%B4%E5%8F%91%E4%BC%9A%E5%91%98%E5%AF%BC%E5%85%A5.xlsx")
      );
    },
    goBack() {
      history.back();
    },
    changeFunDelete_good(val) {
      this.deleteList = val;
    },
    // 批量删除指定会员
    deleted() {
      let self = this;
      if (this.formData.shopList.length) {
        this.formData.shopList = this.formData.shopList.filter(function(item) {
          return self.deleteList.indexOf(item) == -1;
        });
      }
    },
    // 弹窗确定选择会员页面
    confirmSelectMember() {
      // console.log(this.singleH5Page);
      if (this.singleH5Page.length === 0) {
        this.$message.error("请先选择会员");
        return false;
      }
      this.formData.shopList = this.formData.shopList.concat(this.singleH5Page);
      for (var i = 0; i < this.formData.shopList.length; i++) {
        let item = this.formData.shopList[i];
        item.memberName = item.name;
        item.memberCompanyId = item.id;
      }
      this.formData.shopList = this.uniqueMemberId(this.formData.shopList);
      this.dialogH5Page = false;
    },
    init() {
      if (this.linkName != undefined) {
        this.formData.creator = this.linkName;
      } else {
        this.formData.creator = this.mobile;
      }
    },
    clickSelectH5Page() {
      this.selectData.phone = "";
      this.h5ConfigList(this.pageDataH5Page.pageSize, 1);
      this.dialogH5Page = true;
    },
    // 查询会员等级
    getStore(pageSize, pageNum) {
      let data = {
        levelName: this.selectData.storeName,
        pageNum: pageNum,
        pageSize: pageSize
      };
      if (this.selectData.storeType) {
        data.shopId = this.selectData.storeType;
        if (this.isShop != "0" && data.shopId == this.merchantId) {
          data.isCompany = true;
        } else {
          data.isCompany = false;
        }
      } else {
        data.shopId = this.merchantId;
        data.isCompany = false;
      }
      listMemberLevelOfTicket(data).then(res => {
        if (res.code == 200) {
          this.tableDataDialogStore = res.data.list;
          this.pageDataStore.totalItems = res.data.totalRecord;
        }
      });
    },
    // 查询可用优惠券体验券
    getCard(pageSize, pageNum) {
      let data = {
        pageSize: pageSize,
        pageNo: pageNum,
        orgId: this.merchantId,
        ticketTypeList: "0,1",
        ticketState: 0,
        mark: 0,
        ticketName: this.selectData.ticketName
      };
      findMarketTicketListPage(data).then(res => {
        if (res.code == 200) {
          res.data.list.forEach(element => {
            element.sendCount = "";
          });
          this.tableDataDialogTicket = res.data.list;
          this.pageDataTicket.totalItems = res.data.totalPage;
        }
      });
    },
    // 会员列表查询
    h5ConfigList(pageSize, pageNum) {
      let data = {
        phone: this.selectData.phone,
        pageNum: pageNum,
        pageSize: pageSize,
        companyId: this.merchantId
      };
      memberListPage(data).then(res => {
        this.tableDataDialogH5Page = res.data.list;
        this.pageDataH5Page.totalItems = res.data.totalRecord;
      });
    },
    // 自定义会员选择商品品类
    commodityCategoryfun() {
      getTreeList({}).then(res => {
        if (res.code == 200) {
          this.commodityCategoryfunList = res.data;
        }
      });
    },
    // 自定义会员选择商品品牌
    commodityBrand() {
      let data = {
        shopId: this.merchantId
      };
      brandDetail(data).then(res => {
        if (res.code == 200) {
          this.commodityBrandList = res.data;
        }
      });
    },
    //查询会员等级
    getMemberLevel() {
      let data = {
        companyId: this.merchantId,
        keyword: "",
        status: ""
      };
      listMemberLevel(data).then(res => {
        if (res.code == 200) {
          this.memberList = res.data;
        }
      });
    },
    // 筛选可用自定义会员
    getMemNum() {
      if (Number(this.formData.moneyMin) > Number(this.formData.moneyMax)) {
        this.$message.error("自定义会员消费最低金额不能大于最高金额！");
        return false;
      }
      let data = {
        shopId: this.merchantId,
        orderType: this.formData.orderType,
        startDate: this.formData.orderDate[0],
        endDate: this.formData.orderDate[1],
        saleNum: this.formData.payNum,
        orderPriceMin: this.formData.moneyMin,
        orderPriceMax: this.formData.moneyMax,
        classifyId: this.formData.typeId,
        brandId: this.formData.brandId
      };
      ticketSendCountMember(data).then(res => {
        if (res.code == 200) {
          this.statisticsNum = Number(res.data.count);
          this.formData.peopleNum = Number(res.data.count);
          this.countList = res.data.list;
        }
      });
    },
    // 删除一条选择的优惠券
    deleteTicket(index, rows) {
      rows.splice(index, 1);
    },
    // 删除一条选择的门店
    deleteStore(index, rows) {
      rows.splice(index, 1);
    },
    // 点击选择会员等级
    clickSelectStores() {
      this.selectData.storeType = "";
      this.selectData.storeName = "";
      this.getStore(this.pageDataStore.pageSize, 1);
      this._selectBaseShopPageList();
      this.dialogStore = true;
    },
    // 点击选择优惠券
    clickSelectTickets() {
      this.selectData.ticketName = "";
      this.getCard(this.pageDataTicket.pageSize, 1);
      this.dialogTicket = true;
    },
    // 弹窗中门店多选
    selectStore(val) {
      this.mutableStore = val;
    },
    // 弹窗多选优惠券
    selectTicket(val) {
      this.mutableTicket = val;
    },
    // 弹窗h5页面单选
    selectH5Page(val) {
      this.singleH5Page = val;
      // console.log(val);
      // console.log(this.singleH5Page);
    },
    // 弹窗会员等级里面的查询
    searchStore() {
      this.getStore(this.pageDataStore.pageSize, 1);
    },
    searchSelect() {
      this.h5ConfigList(this.pageDataH5Page.pageSize, 1);
    },
    searchTicket() {
      this.getCard(this.pageDataTicket.pageSize, 1);
    },
    // 弹窗里确定选择等级弹窗
    confirmSelectStore() {
      if (this.mutableStore.length === 0) {
        this.$message.error("请先选择等级");
        return false;
      }
      this.formData.gradeList = this.mutableStore;
      // .concat(
      //   this.mutableStore
      // );
      for (let i = 0; i < this.formData.gradeList.length - 1; i++) {
        for (let j = i + 1; j < this.formData.gradeList.length; j++) {
          if (this.formData.gradeList[i].id == this.formData.gradeList[j].id) {
            this.formData.gradeList.splice(j, 1);
          }
        }
      }
      this.$refs.multipleTableStore.clearSelection();
      this.dialogStore = false;
    },
    // 弹窗确定选择优惠券
    confirmSelectTicket() {
      if (this.mutableTicket.length === 0) {
        this.$message.error("请先选择优惠券");
        return false;
      }
      for (let j = 0; j < this.mutableTicket.length; j++) {
        this.mutableTicket[j].sendCount = "1";
      }
      this.formData.ticketList = this.formData.ticketList.concat(
        this.mutableTicket
      );
      for (let j = 0; j < this.formData.ticketList.length; j++) {
        this.formData.ticketList[j].ticketId = this.formData.ticketList[j].id;
      }
      // console.log(this.formData.ticketList);
      this.formData.ticketList = this.uniqueId(this.formData.ticketList);
      this.$refs.multipleTableTicket.clearSelection();
      this.dialogTicket = false;
    },
    //订单类型改变 重置
    empty() {
      this.formData.orderDate = [];
      this.formData.payNum = "";
      this.formData.moneyMin = null;
      this.formData.moneyMax = null;
      this.formData.typeId = "";
      this.formData.brandId = "";
      this.formData.peopleNum = 0;
      this.statisticsNum = 0;
    },
    // 重置自定义会员条件
    resetman() {
      this.formData.orderDate = [];
      this.formData.orderType = "";
      this.formData.payNum = "";
      this.formData.moneyMin = null;
      this.formData.moneyMax = null;
      this.formData.typeId = "";
      this.formData.brandId = "";
      this.formData.peopleNum = 0;
      this.statisticsNum = 0;
    },
    // 选择活动人群
    changePeopleRange() {
      if (this.formData.activityCrowd == "2") {
        this.Grade = true;
      } else {
        this.Grade = false;
      }
      if (this.formData.activityCrowd == "3") {
        this.diymem = true;
      } else {
        this.diymem = false;
      }
      if (this.formData.activityCrowd == "4") {
        this.memLevel = true;
      } else {
        this.memLevel = false;
      }
    },
    //保存直接发券
    saveAct(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let Datas = {};
          Datas.orgId = this.merchantId;
          Datas.ticketBatchName = this.formData.activityName;
          Datas.activityCrowd = this.formData.activityCrowd; // 活动人群
          Datas.sendType = this.paymentTime;
          if (this.paymentTime == 1) {
            Datas.ticketSendTime = this.formData.fixedTime;
          }
          Datas.creator = this.formData.creator;
          if (this.formData.activityCrowd == "2") {
            // 会员等级
            if (this.formData.gradeList.length === 0) {
              this.$message.error("请选择会员等级！");
              return false;
            }
            var arrid = [];
            // Datas.activityCrowdRue = this.formData.gradeList;
            for (let i = 0; i < this.formData.gradeList.length; i++) {
              arrid.push(this.formData.gradeList[i].id);
            }
            Datas.activityCrowdRue = arrid.join();
          } else if (this.formData.activityCrowd == "3") {
            // 自定义会员
            if (
              Number(this.formData.moneyMin) > Number(this.formData.moneyMax)
            ) {
              this.$message.error("自定义会员消费最低金额不能大于最高金额！");
              return false;
            }
            if (this.statisticsNum === 0) {
              this.$message.error(" 自定义会员统计数不能为0！");
              return false;
            }
            Datas.memberIdList = this.countList.join();
            var arr = {};
            Datas.activityCrowdRue = {};
            arr.orderType = this.formData.orderType;
            arr.orderStartTime = this.formData.orderDate[0];
            arr.orderEndTime = this.formData.orderDate[1];
            arr.consumeTimes = this.formData.payNum;
            arr.orderStartAmount = this.formData.moneyMin;
            arr.orderEndAmount = this.formData.moneyMax;
            arr.classifyId = this.formData.typeId;
            arr.brandId = this.formData.brandId;
            arr.peopleNum = this.formData.peopleNum;
            arr.count = this.statisticsNum;
            Datas.activityCrowdRue = JSON.stringify(arr);
          } else if (this.formData.activityCrowd == "4") {
            if (this.formData.shopList.length === 0) {
              this.$message.error("请选择指定会员！");
              return false;
            }
            Datas.memberList = JSON.stringify(this.formData.shopList);
            // console.log(this.formData.shopList);
          }
          for (let j = 0; j < this.formData.ticketList.length; j++) {
            let items = this.formData.ticketList[j];
            items.ticketId = items.id;
            if (!items.sendCount) {
              this.$message.error("请填写优惠券发放数量");
              return false;
            }
          }
          Datas.ticketList = JSON.stringify(this.formData.ticketList);
          if (util.getQuery().id !== undefined) {
            Datas.id = util.getQuery().id;
          }
          saveOrUpdateTicketSend(Datas).then(res => {
            if (res.code == "200") {
              util.routerTo("/marketing-center/company-active/hair-coupon");
            }
          });
        } else {
          this.$message.error("请检查必填信息");
          return false;
        }
      });
    },
    //查询详情
    details(id) {
      let Datas = {
        id: util.getQuery().id
      };
      selectTicketSendDetail(Datas).then(res => {
        // this.formData = res.data;
        this.formData.activityName = res.data.ticketBatchName;
        this.formData.ticketList = res.data.ticketList;
        this.paymentTime = res.data.sendType;
        this.formData.activityCrowd = res.data.activityCrowd.toString(); // 活动人群
        this.formData.fixedTime = util.getdatetime(res.data.ticketSendTime);
        this.changePeopleRange();
        if (res.data.activityCrowd == "2") {
          // 活动人群
          this.formData.activityCrowd = "2";
          for (let i = 0; i < res.data.levelList.length; i++) {
            res.data.levelList[i].shopName =
              res.data.levelList[i].levelBelongTo;
          }
          this.formData.gradeList = res.data.levelList;
        } else if (res.data.activityCrowd == "3") {
          // // 会员等级
          let arr = res.data.activityCrowdRue;
          this.formData.orderType = arr.orderType;
          // this.formData.orderDate[1] = "2019-10-11";
          this.$set(this.formData.orderDate, 0, arr.orderStartTime);
          this.$set(this.formData.orderDate, 1, arr.orderEndTime);
          // this.formData.orderDate[1] = arr.orderEndTime;
          this.countList = res.data.memberIdList.split(",");
          this.formData.payNum = arr.consumeTimes;
          this.formData.moneyMin = arr.orderStartAmount;
          this.formData.moneyMax = arr.orderEndAmount;
          if (arr.classifyId) {
            this.formData.typeId = arr.classifyId;
          }
          if (arr.brandId) {
            this.formData.brandId = arr.brandId;
          }
          this.formData.peopleNum = arr.peopleNum;
          this.statisticsNum = arr.count;
        } else if (res.data.activityCrowd == "4") {
          // 自定义会员
          for (let i = 0; i < res.data.memberList.length; i++) {
            res.data.memberList[i].name = res.data.memberList[i].memberName;
          }
          this.formData.shopList = res.data.memberList;
        }
      });
    }
  }
};
</script>

<style>
.activityPeople .el-radio {
  line-height: 2;
}
</style>

<style scoped>
.file {
  position: relative;
  top: 10px;
  display: inline-block;
  background: #409eff;
  border: 1px solid #409eff;
  border-radius: 4px;
  padding: 6px 13px;
  margin: auto 10px;
  overflow: hidden;
  color: #fff;
  text-decoration: none;
  text-indent: 0;
  line-height: 18px;
  font-size: 10px;
}
.file input {
  position: absolute;
  right: 0;
  top: 0;
  opacity: 0;
}
.file:hover {
  background: #409eff;
  border-color: #409eff;
  color: #fff;
  text-decoration: none;
}
.conserve {
  width: 100%;
  margin-bottom: 20px;
  margin-top: 20px;
}
.conserve-box {
  width: 200px;
  margin: 0 auto;
}
.infon_text_t {
  margin-right: 10px;
}
.ts {
  color: #909399;
}
.sub {
  margin-top: 30px;
  width: 100%;
  text-align: center;
  margin-bottom: 100px;
}
.activityPeople .memLevelContent {
  margin: 10px 0;
  padding: 10px;
  background-color: #ffffff;
}
.activityPeople .memLevelContent-list {
  width: 600px;
  margin: 10px 0;
  padding: 10px;
  background-color: #ffffff;
}
</style>
